import knex from '../db/sql'
import {Context, MetheodType, Next} from 'TYPE';
import path from 'path'
import fs from 'fs'
import config from '../config/config.dev'
import send from 'koa-send'
import AdminController from './admin.controller';
import UserController from './user.controller';
let {UPLOAD_PATH} = config

export default class FileController {
    // @AdminController.checkIsAdmin
    @UserController.checkLogin
    static async uploadImage(ctx: Context, next: Next) {
        let image_path: string = null
        if (ctx.request.files && ctx.request.files.image) {
            image_path = (ctx.request.files.image as any).newFilename as string
        }
        if (!image_path) {
            ctx.cd = 1
            ctx.msg = "上传失败！！"
            ctx.return = null
        }else{
            ctx.cd = 0
            ctx.msg = "上传成功"
            ctx.return = image_path
        }
        await next()
    }
    static async getFile(ctx: Context, next: Next) {
        next = next || (() => {}) as any
        let filename = ctx.params.filename
        const filepath = path.join(UPLOAD_PATH, filename);
        
        if (!fs.existsSync(filepath)) {
            ctx.cd = 1
            ctx.msg = "文件不存在！！"
        } else {
            // console.log(filepath);
            ctx.cd = 0
            ctx.attachment(filepath)
            await send(ctx, filename, {root: UPLOAD_PATH})
        }
        next()
    }
}
